package com.example.inventoryservice.company.strategy;


import com.example.inventoryservice.company.CompanyFinancialData;
import com.example.inventoryservice.company.IncomeTaxStrategy;
import com.example.inventoryservice.company.TaxCalculationResult;

import java.math.BigDecimal;
import java.time.LocalDate;

// 具体策略: 小微企业所得税计算
public class SmallEnterpriseTaxStrategy implements IncomeTaxStrategy {
    @Override
    public TaxCalculationResult calculate(CompanyFinancialData data) {
        // 小微企业所得税优惠: 应纳税所得额不超过300万，减按25%计入，按20%税率征收
        BigDecimal taxableIncome = data.getTaxableIncome();
        BigDecimal taxRate = new BigDecimal("0.20"); // 20%税率

        // 计算基准税额
        BigDecimal baseTax;
        if (taxableIncome.compareTo(new BigDecimal("3000000")) <= 0) {
            baseTax = taxableIncome.multiply(new BigDecimal("0.25")).multiply(taxRate);
        } else {
            // 超过300万部分不享受优惠
            BigDecimal preferentialPart = new BigDecimal("3000000").multiply(new BigDecimal("0.25")).multiply(taxRate);
            BigDecimal excessPart = taxableIncome.subtract(new BigDecimal("3000000")).multiply(new BigDecimal("0.25"));
            baseTax = preferentialPart.add(excessPart);
        }

        // 额外减免: 新成立企业前两年再减半
        BigDecimal deductions = BigDecimal.ZERO;
        LocalDate now = LocalDate.now();
        if (now.minusYears(2).isBefore(data.getEstablishmentDate())) {
            deductions = baseTax.multiply(new BigDecimal("0.5"));
        }

        BigDecimal finalTax = baseTax.subtract(deductions);
        BigDecimal prepaidTax = data.getQuarterlyTaxPrepayments().stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        return new TaxCalculationResult(taxableIncome, taxRate, baseTax, deductions, finalTax, prepaidTax);
    }

    @Override
    public boolean isApplicable(CompanyFinancialData data) {
        // 判断是否符合小微企业标准
        return "SMALL_ENTERPRISE".equals(data.getCompanyType()) && data.getEmployeeCount() <= 300 && data.getTotalAssets().compareTo(new BigDecimal("50000000")) <= 0 && data.getTaxableIncome().compareTo(new BigDecimal("3000000")) <= 0;
    }
}
